import os
from datetime import datetime
from flask import render_template,request,redirect,flash
from app import app
from models import User,Post
from forms import PostForm,EditForm
from exts import db
from flask_login import login_required,current_user
from werkzeug.utils import secure_filename


ALLOWED_EXTENSIONS =set(['png','jpg','jpeg','gif'])
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS  # rsplit()是 Python 字符串的一个方法。它的主要作用是从字符串的右侧（即末尾）开始分割字符串。

@app.route("/",methods=["POST","GET"])
@login_required
def index():
    form=PostForm()
    if form.validate_on_submit():
        post=Post(body=form.text.data)
        current_user.posts.append(post)
        db.session.commit()
        flash("add ok. "+datetime.now().strftime("%Y-%m-%d %H:%M:%S"),category="success")    
      
    n_followers=len(current_user.followers)
    n_followed=len(current_user.followed)
    page=request.args.get("page",default=1,type=int)
    posts =Post.query.order_by(Post.timestamp.desc()).paginate(page=page,per_page=2,error_out=False) # 分页
    
    return render_template("index.html",form=form,n_followers=n_followers,n_followed=n_followed,posts=posts)


@app.route("/user_page/<username>")
@login_required
def user_page(username):    
    # print(username)    
    u=User.query.filter_by(username=username).first()
    if u:
        page=request.args.get("page",default=1,type=int)
        posts =Post.query.filter_by(user_id=u.id).order_by(Post.timestamp.desc()).paginate(page=page,per_page=2,error_out=False) # 分页
        return render_template("user_page.html",posts=posts,username=username,user=u)
    else:
        return '404'
    
@app.route("/follow/<username>")
@login_required
def follow(username):   
    pass
    u=User.query.filter_by(username=username).first()
    if u:
        current_user.follow(u)
        db.session.commit()
        page=request.args.get("page",default=1,type=int)
        posts =Post.query.filter_by(user_id=u.id).order_by(Post.timestamp.desc()).paginate(page=page,per_page=2,error_out=False) # 分页
        return render_template("user_page.html",posts=posts,username=username,user=u)
    else:
        return '404'
    
@app.route("/unfollow/<username>")
@login_required
def unfollow(username):  
    pass 
    u=User.query.filter_by(username=username).first()
    if u:
        current_user.unfollow(u)
        db.session.commit()
        page=request.args.get("page",default=1,type=int)
        posts =Post.query.filter_by(user_id=u.id).order_by(Post.timestamp.desc()).paginate(page=page,per_page=2,error_out=False) # 分页
        return render_template("user_page.html",posts=posts,username=username,user=u)
    else:
        return '404'
    
@app.route("/edit_profile",methods=["POST","GET"])
@login_required
def edit_profile():
    form=EditForm()
    if form.validate_on_submit():
        f=form.img.data
        if f.filename=="":
            flash(f"no file !","warning")
            return redirect(request.url)
        if f and allowed_file(f.filename):
            filename = secure_filename(f.filename)
            fileStr=os.path.join("static","assets",filename)     
            f.save(fileStr)
            fileStr="/static/assets/"+filename #需要转换一下再保存进数据库，要不然页面显示不出画面
            current_user.avatar_img=fileStr
            db.session.commit()
            flash(f"success upload {f.filename}!","success")
        else:
            flash(f"error upload {f.filename}!","danger")
    return render_template('edit_profile.html',form=form)
